package com.wcs.exam.dao.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wcs.exam.common.base.page.SqlUtil;
import com.wcs.exam.common.cache.CacheRedis;
import com.wcs.exam.common.constant.RedisConstant;
import com.wcs.exam.dao.po.ExamPaperCiteCountPO;
import com.wcs.exam.dao.ExamDao;
import com.wcs.exam.dao.impl.mapper.ExamMapper;
import com.wcs.exam.dao.impl.mapper.entity.Exam;
import jakarta.validation.constraints.NotNull;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Repository;

import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 考试 持久化实现类
 *
 * @author wcs
 * @since 2025-03-13
 */
@RequiredArgsConstructor
@Repository
public class ExamDaoImpl extends ServiceImpl<ExamMapper, Exam> implements ExamDao {

    @NotNull
    private final CacheRedis cacheRedis;

    @Override
    public <R> List<R> selectObjs(Wrapper<Exam> wrapper, Class<R> classType) {
        List<Map<String, Object>> resultMaps = baseMapper.selectMaps(wrapper);
        if (CollectionUtil.isEmpty(resultMaps)) {
            return Collections.emptyList();
        }
        return BeanUtil.copyToList(resultMaps, classType);
    }

    @Override
    public Integer getMaxSort() {
        return lambdaQuery().orderByDesc(Exam::getSort).last(SqlUtil.limitOne()).oneOpt().map(Exam::getSort).orElse(0);
    }

    @Override
    public Exam getByIdForCache(Long id) {
        Exam exam = cacheRedis.get(RedisConstant.Exam.EXAM_VIEW + id, Exam.class);
        if (ObjectUtil.isEmpty(exam)) {
            exam = getById(id);
            cacheRedis.set(RedisConstant.Exam.EXAM_VIEW + id, exam, 10, TimeUnit.SECONDS);
        }
        return exam;
    }

    @Override
    public List<ExamPaperCiteCountPO> paperCiteCount(Collection<Long> paperIds) {
        LambdaQueryWrapper<Exam> wrapper = new QueryWrapper<Exam>()
                .select("paper_id as paperId, count(1) as count")
                .lambda()
                .in(Exam::getPaperId, paperIds)
                .groupBy(Exam::getPaperId);
        return selectObjs(wrapper, ExamPaperCiteCountPO.class);
    }
}
